<template>
	<view>
		<view class="tips white u-font-24 align-center" :class="{ 'show':ajax.loading }" @tap="getHistoryMsg">
			{{ajax.loadText}}
		</view>
		<view class="box-1" id="list-box">
			<view class="order-pane" v-if="orderDetail.id">
				<view class="order-view">
					<view class="u-flex-1 w-0">
						<view class="u-font-30 font-medium u-line-1">
							{{orderDetail.title+orderDetail.title}}
						</view>
						<view class="u-flex u-col-center">
							<view class="price u-type-error u-m-r-10">
								<text class="u-font-30">{{orderDetail.price}}</text>
							</view>
							<text class="u-font-20 u-light-color">交易前聊一聊</text>
						</view>
					</view>
					<view class="u-m-t-40" v-if="orderDetail.uid!==userInfo.uid">
						<u-button type="primary" size="mini" hover-class="none" @click="orderAction">
							{{ options.sid?'立即预约':'预约接单' }}
						</u-button>
					</view>
				</view>
			</view>
			<view class="talk-list">
				<view class="tips-box">
					温馨提示：为了您的合法权益不受损害，平台建议您在使用帮 把关APP沟通前，仔细了解对方信息，谨防各类诈骗陷阱。
				</view>
				<view v-for="(item,index) in talkList" :key="index" :id="`msg-${item.id}`">
					<view class="align-center u-font-28 u-light-color u-m-25">
						{{formateTime(index)}}
					</view>
					<view class="item u-flex" :class=" item.uid == userInfo.uid ? 'push':'pull' ">
						<image :src="item.avatar" mode="aspectFill" class="pic" @click="toProfile(item.uid)"></image>
						<view class="content">{{item.msn}}</view>
					</view>
				</view>
			</view>
		</view>
		<view class="box-2">
			<view class="u-flex">
				<view class="flex_grow">
					<input type="text" class="content" v-model="content" placeholder="新消息" placeholder-style="color:#DDD;"
						:cursor-spacing="6">
				</view>
				<button class="send" @tap="send">发送</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				talkList: [],
				ajax: {
					rows: 20, //每页数量
					page: 1, //页码
					flag: true, // 请求开关
					loading: true, // 加载中
					loadText: '正在获取消息'
				},
				content: '',
				options: {},
				userInfo: {},
				orderDetail: {}
			}
		},
		onLoad(option) {
			this.userInfo = this.$store.state.vuex_userInfo
			this.options = option || {}
			this.getOrderDetail()
			uni.setNavigationBarTitle({
				title: option.name
			})
			uni.$off()
		},
		onUnload() {
			uni.$off()
			this.$store.dispatch('closeConnect')
		},
		mounted() {
			this.$nextTick(() => {
				this.getHistoryMsg();
			});
		},
		onPageScroll(e) {
			if (e.scrollTop < 5) {
				this.getHistoryMsg();
			}
		},
		methods: {
			// 是否显示时间
			formateTime(index) {
				let time = "";
				const msgdata = this.talkList[index];
				const currentDate = new Date();
				const currentYear = currentDate.getFullYear();
				const currentMonth = currentDate.getMonth();
				const currentDay = currentDate.getDate();



				if (index === 0) {
					time = msgdata._add_time
				} else {
					const preMsg = this.talkList[index - 1];
					const preDate = new Date(preMsg._add_time)
					const thisDate = new Date(msgdata._add_time)
					const diffTimes = thisDate.getTime() - preDate.getTime()
					if (diffTimes > 10 * 60 * 1000) {
						time = preMsg._add_time
					} else {
						return ''
					}
				}

				const targetDate = new Date(time)
				const targetYear = targetDate.getFullYear();
				const targetMonth = targetDate.getMonth();
				const targetDay = targetDate.getDate();

				if (currentYear === targetYear && currentMonth === targetMonth && currentDay === targetDay) {
					return `${targetDate.getHours()>9?targetDate.getHours():'0'+targetDate.getHours()}:${targetDate.getMinutes()>9?targetDate.getMinutes():'0'+targetDate.getMinutes()}`
				} else {
					return `${targetYear}/${targetMonth+1}/${targetDay} ${targetDate.getHours()>9?targetDate.getHours():'0'+targetDate.getHours()}:${targetDate.getMinutes()>9?targetDate.getMinutes():'0'+targetDate.getMinutes()}`
				}
			},
			// 获取历史消息
			getHistoryMsg() {
				if (!this.ajax.flag) {
					return; //
				}
				let get = async () => {
					this.hideLoadTips();
					this.ajax.flag = false;
					let data = await this.joinHistoryMsg();

					console.log('----- 模拟数据格式，供参考 -----');
					console.log(data); // 查看请求返回的数据结构 

					// 获取待滚动元素选择器，解决插入数据后，滚动条定位时使用
					let selector = '';

					if (this.ajax.page > 1) {
						// 非第一页，则取历史消息数据的第一条信息元素
						selector = `#msg-${this.talkList[0].id}`;
					} else {
						// 第一页，则取当前消息数据的最后一条信息元素
						if (data.length > 0) {
							selector = `#msg-${data[data.length-1].id}`;
						}
					}

					// 将获取到的消息数据合并到消息数组中
					this.talkList = [...data, ...this.talkList];

					this.$nextTick(() => {
						// 设置当前滚动的位置
						this.talkList.length > 0 && this.setPageScrollTo(selector);

						this.hideLoadTips(true);

						uni.$on('pullmsg', (msg) => {
							// const msgdata = JSON.parse(msg);
							console.log(msg);
							this.reciveMessage(msg)
						})
						this.$store.dispatch('createConnect')
						if (data.length < this.ajax.rows) {
							// 当前消息数据条数小于请求要求条数时，则无更多消息，不再允许请求。
							// 可在此处编写无更多消息数据时的逻辑
						} else {
							this.ajax.page++;
							// 延迟 200ms ，以保证设置窗口滚动已完成
							setTimeout(() => {
								this.ajax.flag = true;
							}, 200)
						}

					})
				}
				get();
			},
			// 历史记录消息
			joinHistoryMsg() {
				return new Promise((done, fail) => {
					this.$u.api.messageHistory({
						toUid: this.options.uid,
						page: this.ajax.page,
						limit: this.ajax.rows
					}).then(res => {
						console.log(res);
						let data = res.serviceList;
						done(data)
					})
				})
			},
			// 设置页面滚动位置
			setPageScrollTo(selector) {
				let view = uni.createSelectorQuery().in(this).select(selector);
				view.boundingClientRect((res) => {
					uni.pageScrollTo({
						scrollTop: res.top - 30, // -30 为多显示出大半个消息的高度，示意上面还有信息。
						duration: 0
					});
				}).exec();
			},
			// 隐藏加载提示
			hideLoadTips(flag) {
				if (flag) {
					this.ajax.loadText = '消息获取成功';
					setTimeout(() => {
						this.ajax.loading = false;
					}, 300);
				} else {
					this.ajax.loading = true;
					this.ajax.loadText = '正在获取消息';
				}
			},
			// 接收消息
			reciveMessage(msg) {
				if (msg.type == 'success') {
					this.$store.dispatch('sendMessage', {
						data: {
							to_uid: this.options.uid,
							serve_id: this.options.sid,
							demand_id: this.options.did
						},
						type: 'to_chat'
					})
				}
				if (msg.type == 'reply' || msg.type == 'chat') {
					this.talkList.push(msg.data);
					this.$nextTick(() => {
						// 清空内容框中的内容
						this.content = '';
						uni.pageScrollTo({
							scrollTop: 999999, // 设置一个超大值，以保证滚动条滚动到底部
							duration: 0
						});
					})
				}
			},
			// 发送信息
			send() {
				if (!this.content) {
					uni.showToast({
						title: '请输入有效的内容',
						icon: 'none'
					})
					return;
				}
				this.$store.dispatch('sendMessage', {
					data: {
						msn: this.content,
						type: 1,
						to_uid: this.options.uid,
						serve_id: this.options.sid,
						demand_id: this.options.did
					},
					type: 'chat'
				})
			},

			getOrderDetail() {
				if (this.options.sid) {
					this.$u.api.serveDetail(this.options.sid).then(res => {
						this.orderDetail = res;
					})
				}
				if (this.options.did) {
					this.$u.api.demandDetail(this.options.did).then(res => {
						this.orderDetail = res;
					})
				}
			},
			orderAction() {
				if (this.options.sid) {
					if (!this.userInfo.is_real) {
						this.$u.route("/pages/subpage/profile/autonym")
					} else {
						this.$u.route('/pages/subpage/order/action_user', {
							id: this.options.sid,
							role: 'user'
						})
					}
				}
				if (this.options.did) {
					if (!this.userInfo.is_real) {
						this.$u.route("/pages/subpage/profile/autonym")
					} else {
						this.$u.route('/pages/subpage/order/action_dem', {
							id: this.options.did
						})
					}
				}
			},
			// 查看主页
			toProfile(uid) {
				this.$u.route('/pages/subpage/profile/index', {
					id: uid
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F3F3F3;
		font-size: 28rpx;
	}

	/* 加载数据提示 */
	.tips {
		position: fixed;
		left: 0;
		top: var(--window-top);
		width: 100%;
		z-index: 9;
		background-color: rgba(0, 0, 0, 0.15);
		height: 72rpx;
		line-height: 72rpx;
		transform: translateY(-80rpx);
		transition: transform 0.3s ease-in-out 0s;

		&.show {
			transform: translateY(0);
		}
	}

	.box-1 {
		width: 100%;
		height: auto;
		padding-bottom: 200rpx;
		box-sizing: content-box;

		/* 兼容iPhoneX */
		margin-bottom: 0;
		margin-bottom: constant(safe-area-inset-bottom);
		margin-bottom: env(safe-area-inset-bottom);
	}

	.flex_grow {
		width: 0;
		flex-grow: 1;
	}

	.box-2 {
		position: fixed;
		left: 0;
		width: 100%;
		bottom: 0;
		height: auto;
		z-index: 2;
		border-top: #e5e5e5 solid 1px;
		box-sizing: content-box;
		background-color: #F3F3F3;

		/* 兼容iPhoneX */
		padding-bottom: 0;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);

		&>view {
			padding: 0 20rpx;
			height: 100rpx;
		}

		.content {
			background-color: #fff;
			height: 64rpx;
			padding: 0 20rpx;
			border-radius: 32rpx;
			font-size: 28rpx;
		}

		.send {
			background-color: $u-type-primary;
			color: #fff;
			height: 64rpx;
			margin-left: 20rpx;
			border-radius: 32rpx;
			padding: 0;
			width: 120rpx;
			line-height: 62rpx;
			font-size: 28rpx;

			&:active {
				background-color: #5fc496;
			}
		}
	}

	.talk-list {
		padding-bottom: 20rpx;

		.tips-box {
			padding: 30rpx 50rpx;
			color: $u-light-color;
			font-size: 24rpx;
		}

		/* 消息项，基础类 */
		.item {
			padding: 20rpx 20rpx 0 20rpx;
			align-items: flex-start;
			align-content: flex-start;
			color: #333;

			.pic {
				width: 92rpx;
				height: 92rpx;
				border-radius: 50%;
				border: #fff solid 1px;
			}

			.content {
				padding: 20rpx;
				border-radius: 4px;
				max-width: 500rpx;
				word-break: break-all;
				line-height: 52rpx;
				position: relative;
			}

			/* 收到的消息 */
			&.pull {
				.content {
					margin-left: 32rpx;
					background-color: #fff;

					&::after {
						content: '';
						display: block;
						width: 0;
						height: 0;
						border-top: 16rpx solid transparent;
						border-bottom: 16rpx solid transparent;
						border-right: 20rpx solid #fff;
						position: absolute;
						top: 30rpx;
						left: -18rpx;
					}
				}
			}

			/* 发出的消息 */
			&.push {
				/* 主轴为水平方向，起点在右端。使不修改DOM结构，也能改变元素排列顺序 */
				flex-direction: row-reverse;

				.content {
					margin-right: 32rpx;
					background-color: $u-type-primary;
					color: #fff;

					&::after {
						content: '';
						display: block;
						width: 0;
						height: 0;
						border-top: 16rpx solid transparent;
						border-bottom: 16rpx solid transparent;
						border-left: 20rpx solid $u-type-primary;
						position: absolute;
						top: 30rpx;
						right: -18rpx;
					}
				}
			}
		}
	}

	.order-pane {
		position: sticky;
		background-color: #fff;
		top: 0;
		z-index: 999;
	}

	.order-view {
		display: flex;
		padding: 28rpx;
		border-radius: 20rpx;

		&:before {
			content: "";
			display: inline-block;
			width: 10rpx;
			height: 10rpx;
			border-radius: 50%;
			background-color: #999;
			margin-right: 16rpx;
			margin-top: 16rpx;
		}
	}
</style>